package init

import (
	"gin-wheel/global"
	"gin-wheel/pkg"
	"gin-wheel/pkg/setting"
	"gin-wheel/pkg/validator"
	"strings"

	"gorm.io/gorm"
)

func setupAllSetting() error {
	/*
	   读取所有的config配置 初始化设置
	*/

	// 读取配置信息
	s, err := setting.NewSetting(strings.Split(global.BasePath+"/configs/", ",")...)
	if err != nil {
		panic(err)
	}
	var multiSetting setting.MysqlMultiSetting
	err = s.ReadSection("Mysql", &multiSetting)
	if err != nil {
		panic(err)
	}

	// 读取http配置到全局http变量
	err = s.ReadSection("HttpServer", &global.ServerSetting)
	if err != nil {
		panic(err)
	}

	// 读取jwt配置到全局http变量
	err = s.ReadSection("JWTToken", &global.JWTSetting)
	if err != nil {
		panic(err)
	}

	// 读取hasids设置到全局
	err = s.ReadSection("HashIds", &global.HashIdsSetting)
	if err != nil {
		panic(err)
	}

	// 雪花算法配置
	err = s.ReadSection("SnowFlake", &global.SnowFlakeSetting)
	if err != nil {
		panic(err)
	}

	// redis配置
	err = s.ReadSection("Redis", &global.RedisSetting)
	if err != nil {
		panic(err)
	}

	// redis进程池
	global.RedisPool = pkg.RedisPool()

	// 读取数据库配置初始化全局gorm
	global.MysqlConnMaps = make(map[string]*gorm.DB)
	for _, connNameInterface := range multiSetting.ConnNames {
		var connName string = connNameInterface.(string)
		var connSetting setting.MysqlConnSetting // 保存数据库配置
		err = s.ReadSection("Mysql."+connName, &connSetting)
		if err != nil {
			panic(err)
		}
		gormDb := pkg.NewGormMysql(connSetting)
		global.MysqlConnMaps[connName] = gormDb
	}

	// 读取logs配置初始化zaplog全局变量
	err = s.ReadSection("Logs", &global.LogsSetting)
	if err != nil {
		panic(err)
	}
	global.ZapLog = pkg.Zap(global.LogsSetting)

	// 初始化翻译器
	global.TransLator = validator.GetTranslator()
	if global.TransLator == nil {
		panic("初始化翻译器失败")
	}

	// 初始化rabbitmq相关变量
	err = s.ReadSection("RabbitMq.HelloWorld", &global.RabbitHelloSetting)
	if err != nil {
		panic(err)
	}
	err = s.ReadSection("RabbitMq.WorkQueue", &global.RabbitWorkQueueSetting)
	if err != nil {
		panic(err)
	}
	err = s.ReadSection("RabbitMq.PublishSubscribe", &global.RabbitPubsubSetting)
	if err != nil {
		panic(err)
	}
	err = s.ReadSection("RabbitMq.Routing", &global.RabbitRouteSetting)
	if err != nil {
		panic(err)
	}
	err = s.ReadSection("RabbitMq.Topics", &global.RabbitTopicSetting)
	if err != nil {
		panic(err)
	}
	return nil
}

func init() {
	setupAllSetting()
}
